﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using ClientApp.Communication;
using System.Threading;
using ClientApp.UtilClasses;
using System.Net;

namespace ClientApp.Client_Life_Cycle
{
    class ClientProgram
    {
        ///-------------------------------------------------------------------------------------------------
        /// <summary>   Default constructor. </summary>
        ///
        /// <remarks>   Adrian, 08/11/2015. </remarks>
        ///-------------------------------------------------------------------------------------------------

        private Thread mCheckProcessThread;
        public Thread mListeningThread;

        public ClientProgram()
        {
            Console.WriteLine("Listning for server and monitoring process");

            mListeningThread = new Thread(() => LifeCycle());
            mListeningThread.Start();
        }

        public static string GetLocalIPAddress()
        {
            var host = Dns.GetHostEntry(Dns.GetHostName());
            foreach (var ip in host.AddressList)
            {
                //if (ip.AddressFamily == AddressFamily.InterNetwork)
                if (ip.IsIPv6LinkLocal == false && ip.AddressFamily == AddressFamily.InterNetwork)
                {

                    if (Convert.ToInt32(ip.ToString().Split('.')[0]) < 100)
                        return ip.ToString();
                }
            }
            throw new Exception("Local IP Address Not Found!");
        }

        public void LifeCycle()
        {
             string port = ConfigurationManager.AppSettings["MyPort"];
             string ipAddress = GetLocalIPAddress();
             Socket listener = Communication.Communication.BindToSocket(ipAddress, Convert.ToInt32(port));

            while(true)
            {
                //it will receive and execute 
                //need to create a client listener 
                //and executue accoridngly 
                Socket handler = Communication.Communication.ConnectToAClient(listener);
                String data = Communication.Communication.ListenForDataFromServer(handler);
                Communication.Communication.CloseConnection(handler);

                int commandType = Convert.ToInt32(data.Split(new string[]{"<EOF>"}, StringSplitOptions.RemoveEmptyEntries)[0]);

                switch (commandType)
                {
                    // start process
                    case 0:
                    {
                         string processName = ConfigurationManager.AppSettings["ProcessName"];
                        ProcessHelperFunctions.StartProcess();
                        //run the checker, after process has exited, send job temintaion message
                        mCheckProcessThread = new Thread(()=>
                        {
                            ProcessHelperFunctions.CheckProcessRunning(processName);
                            Communication.Communication.SendJobTerminated();
                        });
                        //start thread data
                        mCheckProcessThread.Start();
                        Communication.Communication.SendJobStarted();

                        break;
                    }

                    case 1:
                    {
                        string processName = ConfigurationManager.AppSettings["ProcessName"];
                        ProcessHelperFunctions.CloseProcess(processName);
                        Communication.Communication.SendJobTerminated();
                    }
                    break;
        }

                
            }
        }
    }
}
